from app003.models import Book
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import BookSerializer

class BookViewCR(APIView):
    def get(self, request):
        book_all = Book.objects.all()
        ser = BookSerializer(book_all, many=True)
        return Response({
            'code': 100,
            'msg': 'get',
            'result': ser.data
        })

    def post(self, request):
        data = request.data
        ser = BookSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({
                'code': 100,
                'msg': '添加成功',
                'result': ser.data
            })
        else:
            return Response({
                'code': 101,
                'msg': ser.errors,
            })


class BookViewRUD(APIView):
    def get(self, request, tid):
        book = Book.objects.filter(pk=tid).first()
        if not book:
            return Response({'code': 101, 'msg': '当前书籍不存在'})
        ser = BookSerializer(instance=request.data)
        return Response({'code': 100, 'msg': f'查询指定【{tid}】成功', 'result': ser.data})

    def put(self, request, tid):
        book = Book.objects.filter(pk=tid).first()
        if not book:
            return Response({'code': 101, 'msg': '当前书籍不存在'})
        ser = BookSerializer(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': f'修改指定【{tid}】成功', 'result': ser.data})
        else:
            return Response({
                'code': 101,
                'msg': ser.errors,
            })

    def delete(self, request, tid):
        Book.objects.filter(pk=tid).delete()
        return Response({'code': 100, 'msg': '删除成功'})
